package com.liao.furns.filter;

import com.google.gson.Gson;
import com.liao.furns.pojo.Member;
import com.liao.furns.utils.WebUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lzp
 * @version 1.0
 * lzpnb!
 */
public class AuthFilter implements Filter {
    private List<String> excludedUrls;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludedUrls1 = filterConfig.getInitParameter("excludedUrls");
        String[] split = excludedUrls1.split(",");
        excludedUrls = Arrays.asList(split);

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String  url = request.getServletPath();
        System.out.println("url = " + url);
        if(!excludedUrls.contains(url)){
            Member member = (Member)request.getSession().getAttribute("member");
            if(member == null){
                if(!WebUtils.isAjaxRequest(request)){
                    request.getRequestDispatcher("/views/member/login.jsp").forward(servletRequest,servletResponse);
                }else {
                    Map<String,Object> resultMap = new HashMap<>();
                    resultMap.put("url","views/member/login.jsp");
                    String resultJson = new Gson().toJson(resultMap);
                    servletResponse.getWriter().write(resultJson);
                }
                return;
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
